<?
include_once $_SERVER['DOCUMENT_ROOT'] . "/library/PHPExcel/Classes/PHPExcel.php";
include_once $_SERVER['DOCUMENT_ROOT'] . "/conf/config.php";

if ($_POST['record_type'] == "ALL") {
	$query = "select * from qr_data";
	
	if($_POST['down_cond'] != '' && $_POST['down_word'] != '')
		$query .= " where " . $_POST['down_cond'] . " like '" . $_POST['down_word'] . "%'";
}
elseif (substr($_POST['record_type'], 0, 2) == "PG") {
	$page = substr($_POST['record_type'], 2, strlen($_POST['record_type'])-1);
	$query = "select * from qr_data ";
	if($_POST['down_cond'] != '' && $_POST['down_word'] != '')
		$query .= "where " . $_POST['down_cond'] . " like '" . $_POST['down_word'] . "%' ";
	$query .= "limit " . ($page-1)*20 . ", 20";
}
else {
	$list = explode(",", $_POST['record_type']);
	$where = " where ";
	foreach ($list as $seq) {
		$where .= "SEQNO ='" . $seq ."' or ";
	}
	
	$where = substr($where, 0, strlen($where) - 4 );
	
	$query = "select * from qr_data" . $where;
}

// 엑셀 템플릿 파일
$file = $_SERVER['DOCUMENT_ROOT'] . "/assets/xls/template.xlsx";

// 출력 파일
$file_name = $_SERVER['HTTP_HOST'] . "." . date("Y.m.d.H.i.s") . ".xlsx";
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/assets/xls/" . $file_name;

$dbconn = @mysql_connect($dbhost, $dbuser, $dbpass);
@mysql_select_db($dbname, $dbconn);

$records = @mysql_query($query, $dbconn);

// 엑셀 파일을 읽어 들인다.
$oReader = PHPExcel_IOFactory::load($file);
$oSheet = $oReader->getActiveSheet();

$row_ndx = 2;

while ($row = @mysql_fetch_row($records))
{
	for($col_ndx = 0; $col_ndx < 26; $col_ndx++)
		$oSheet->getCellByColumnAndRow($col_ndx, $row_ndx)->setValue($row[$col_ndx]);
	
	$row_ndx++;
}

// 데이터베이스 닫는다
@mysql_close($dbconn);

$oWriter = PHPExcel_IOFactory::createWriter($oReader, 'Excel2007');
$oWriter->save($target_file);

// 엑셀 파일을 닫는다.
$oReader->disconnectWorksheets();
unset($oSheet);
unset($oReader);
unset($oWriter);

echo json_encode($file_name);
?>